// pages/my/my.js
const utils = require('../../utils/util')
let db = wx.cloud.database({
    env: 'linyr-6gp7qo8008360a60'
})

let user = db.collection('db_user')
let look = db.collection('db_look')
let pet = db.collection('db_pet')
let like = db.collection('db_like')

Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo: {},
        active: 0,
        lookList: [],
        likeList:[],
        hasUserInfo: false,
        canIUseGetUserProfile: true,
        canIUseOpenData: true,
        isHas: false,
        isShow:false,
        startTime:0,
        endTime:0
    },

    // 删除浏览记录
    detaleLook(event) {
        let that = this;
        console.log(event.currentTarget.dataset.id);
        let id = event.currentTarget.dataset.id
        wx.showModal({
            title: '提示',
            content: '确定要删除吗',
            success(res) {
                if (res.confirm) {
                    look.doc(id).remove({
                        success(res) {
                            // console.log(res);
                            let {
                                errMsg
                            } = res
                            if (errMsg == "document.remove:ok") {
                                that.getLook();
                            }
                        }
                    })
                } else if (res.cancel) {}
            }
        })
    },

    //编写方法，获取用户信息
    getUserInfoFunc(user_nickname, avatarUrl) {
        let that = this;
        let dt = new Date();
        // console.log(utils.formatTime(dt));
        //调用云函数
        wx.cloud.callFunction({
            name: 'home',
            data: {
                user_create_time: utils.formatTime(dt),
                user_nickname,
                avatarUrl
            },
            success(content) {
                // console.log(content);
                let {
                    errMsg,
                    result
                } = content
                if (errMsg == 'cloud.callFunction:ok') {
                    console.log(result);
                    if (result.code == 200) {
                        let {
                            userInfo: {
                                user_nickname,
                                avatarUrl,
                                open_id,
                                user_create_time
                            }
                        } = result;
                        //缓存数据
                        wx.setStorageSync('user_nickname', user_nickname)
                        wx.setStorageSync('avatarUrl', avatarUrl)
                        wx.setStorageSync('open_id', open_id)
                        wx.setStorageSync('user_create_time', user_create_time)
                        wx.setStorageSync('userinfo', JSON.stringify(result.userInfo))
                        wx.setStorageSync('isHas', 1)

                        that.setData({
                            userInfo: result.userInfo
                        })

                        //调用云数据api
                        //查询该用户是否存在，若存在就不需要添加到db_user用户表
                        user.where({
                            user_id: open_id
                        }).get().then(content => {
                            console.log("多个条件==>", content);
                            let {
                                data,
                                errMsg
                            } = content
                            if (errMsg == 'collection.get:ok') {
                                if (data.length == 0) {
                                    //调用数据库API,添加数据库
                                    user.add({
                                        data: {
                                            user_id: open_id,
                                            user_nickname: user_nickname,
                                            user_create_time: user_create_time,
                                            user_avator: avatarUrl
                                        }
                                    })
                                } else {
                                    // wx.showToast({
                                    //     title: '用户已存在',
                                    //     icon: 'none'
                                    // })
                                }
                            }
                        })
                    }
                } else {
                    wx.showToast({
                        title: '用户注册失败',
                        icon: 'error'
                    })
                }
            },
            fail(err) {
                console.log(" 请求失败", err);
            }
        })
    },

    //获取用户信息(昵称，头像) 推荐使用
    getUserProfile(e) {
        wx.getUserProfile({
            // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            desc: '展示用户信息',
            success: (res) => {
                // console.log("2.0", res)
                this.setData({
                    userInfo: res.userInfo,
                    hasUserInfo: true
                })
                //解构赋值 获取用户昵称和头像
                let {
                    userInfo: {
                        nickName,
                        avatarUrl
                    }
                } = res;
                //调用云函数
                this.getUserInfoFunc(nickName, avatarUrl);
            }
        })
    },

    // 得到开始触摸的事件
    getStart(){
        this.setData({
            startTime:Date.now()
        })
    },

    // 去详情
    godetail(event) {
        let _id = event.currentTarget.dataset.id
        console.log(_id);
        let endTime = Date.now()
        let time = endTime - this.data.startTime
        if(time>=70){
            this.setData({
                isShow:!this.data.isShow
            })
        }else{
            wx.navigateTo({
                url: '../detail/detail?id=' + _id,
            })
            this.setData({
                isShow:false
            })
        }
    },

    likeGoDetail(event){
        let _id = event.currentTarget.dataset.id
        wx.navigateTo({
            url: '../detail/detail?id=' + _id,
        })
    },

    async onChange(event) {
        if (event.detail.name == 0) {
            await this.getLook();
        }
        if(event.detail.name == 1){
            this.getLike();
        }
    },

    //获取关注列表
    getLike(){
        like.where({}).get().then(content=>{
            console.log(content);
            let { data,errMsg } = content
            if(errMsg == "collection.get:ok"){
                this.setData({
                    likeList:data
                })
            }
        })
    },
    //得到浏览记录
    getLook() {
        look.where({}).get().then(content => {
            // console.log(content);
            let {
                data,
                errMsg
            } = content
            if (errMsg == 'collection.get:ok') {
                this.setData({
                    lookList: data
                })
                // console.log(this.data.lookList);
            }
        })
    },

    onClickDisabled(event) {
        console.log(event);
        if(event.detail.name==1){
            wx.showToast({
                title: `请先登录!`,
                icon: 'none',
            });
        }else{
            wx.showToast({
                title: `该功能还未开发`,
                icon: 'none',
            });
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let isHas = wx.getStorageSync('isHas')
        if (isHas) {
            let userinfo = JSON.parse(wx.getStorageSync('userinfo'))
            this.setData({
                canIUseGetUserProfile: false,
                hasUserInfo: true,
                userInfo: userinfo
            })
            //获取本地储存的数据
        } else {
            this.setData({
                canIUseGetUserProfile: true
            })
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getLook();
        this.getLike();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})